/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 14, 2012  2:01:42 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.mm.outbound
 * File Name : VwSyncContractService.java
 * TODO
 */
package sap.business.mm.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.MmPocontractorOutb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.MmPocontractorOutbServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import promis.utility.Utilitys;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class VwSyncContractService extends SynchroOutAbstract {
		
	private static final Logger log = Logger.getLogger(VwSyncContractService.class);
	private static MmPocontractorOutbServices mmPocontractorOutbServ = null; 

	/**
	 * 
	 * Date =Nov 12, 2013 : 2:33:51 PM 
	 * CreateBy=Chatree Siangklom
	 * VwSyncContractService
	 * TODO
	 */
	public VwSyncContractService() {
		try {
			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	
	/**
	 * (Javadoc)
	 * @see sap.business.commons.SynchroOutAbstract#SynchroToSap(com.sap.conn.jco.JCoFunction, com.sap.conn.jco.JCoTable, com.sap.conn.jco.JCoStructure, java.util.List)
	 * Date =Nov 12, 2013 : 2:33:58 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, JCoStructure jCoStructure, List<?> value_list) throws Exception {
		
		//Check Is not isEmpty is exit method.
		if(!jcoTable.isEmpty())
		{
			log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
			return;
		}	
		
		if(!CommonService.IsNull(value_list)){
			
			jCoStructure.clear();
			log.info("value_list.size : " + value_list.size());			
			log.info("table.getNumRows : " + jcoTable.getNumRows());
						
			//Header
			MmPocontractorOutb model = (MmPocontractorOutb)value_list.get(0);
			log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId() + " -- DocumentNo : " +  model.getDocumentNo());
			//jcoTable.appendRow();
			//jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
			
			jCoStructure.setValue("CONTRACT_TYPE", model.getContractType());
			jCoStructure.setValue("REQTRACK_NO", model.getDocumentNo());
			jCoStructure.setValue("STATUS", model.getStatus());
			jCoStructure.setValue("PENALTY", model.getPnPerday());
			jCoStructure.setValue("GUATANTEES", model.getRetentionAmount());
			jCoStructure.setValue("WARRANTIES", model.getContractGuaranteeAmount());
			jCoStructure.setValue("BUKRS", model.getSapCompanyCode());
			jCoStructure.setValue("BSART", model.getSapPurchDocType());
			jCoStructure.setValue("BEDAT", model.getContractDate());
			jCoStructure.setValue("EKORG", model.getSapPurchOrg());
			jCoStructure.setValue("EKGRP", model.getSapPurchGroup());
			jCoStructure.setValue("WAERS", model.getCurrencyCode());
			jCoStructure.setValue("LIFNR", model.getSupplierCode());
			
			jCoStructure.setValue("RETTP", "I");
			jCoStructure.setValue("RETPC", "");
			jCoStructure.setValue("DPTYP", "M");
			jCoStructure.setValue("DPAMT", "");
			jCoStructure.setValue("DPDAT", "");
			jCoStructure.setValue("CONTRACT_PROJNO", model.getContractNo());
			
			//Item Detail
			jcoTable.deleteAllRows();
			for (Object obj : value_list) 
	        {
				model = (MmPocontractorOutb)obj;
				log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId() + " -- DocumentNo : " +  model.getDocumentNo());
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
				
				jcoTable.setValue("EBELP", Utilitys.leftPad(model.getInstallmentNumber().toString(), 5, "0"));
				jcoTable.setValue("KNTTP", model.getSapAccAss());
				//jcoTable.setValue("MATNR", Utilitys.leftPad(model.getInstallmentNumber().toString(), 5, "0") + "-" + model.getContUnitSeq())
				
				//Add 2013-03-15
				//DR.TREE
				//Support Multi Unit Line
				jcoTable.setValue("MATNR", model.getInstallmentNumberStr());
				
				jcoTable.setValue("TXZ01", model.getDescription());
				jcoTable.setValue("WERKS", model.getSapPlantCode());
				jcoTable.setValue("LGORT", "0001");
				jcoTable.setValue("MENGE", "1");
				jcoTable.setValue("MEINS", "Job");
				jcoTable.setValue("EINDT", model.getInstallmentDueDate());
				jcoTable.setValue("NETPR", model.getInstallmentAmount());
				
				//jcoTable.setValue("MWSKZ", model.getTaxCode());
				jcoTable.setValue("MWSKZ", "VX");
				
				jcoTable.setValue("TRACK_NO", model.getDocumentNo());
				//jcoTable.setValue("CONTRACT_PROJNO", model.getContractNo());
				jcoTable.setValue("AFNAM", model.getCreatedBy());
				jcoTable.setValue("PS_PSP_PNR", "");
				jcoTable.setValue("ABLAD", model.getModelDesc());
				jcoTable.setValue("WEMPF", model.getModelRevision());
				jcoTable.setValue("ITMPLAN", model.getUnitNumber());
				jcoTable.setValue("WEPOS", "");
				jcoTable.setValue("RETENTION_ITM", model.getRetentionPercent());
				jcoTable.setValue("GUARANTEE_ITM", model.getContractGuaranteePercent());
				jcoTable.setValue("POTYPE_CAT", model.getPoContractType());
				
				jcoTable.setValue("ITEM_STATUS", model.getItemStatus());
				
				//For High Rise
				jcoTable.setValue("ACT_CODE", model.getActivityGroupCode());
				
	        }
		}
		
		super.SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
	}

	/**
	 * (Javadoc)
	 * @see sap.business.commons.SynchroOutAbstract#CallbackMessageFromSap(com.sap.conn.jco.JCoTable)
	 * Date =Nov 12, 2013 : 2:34:28 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		List<MmPocontractorOutb> lst = new ArrayList<MmPocontractorOutb>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				MmPocontractorOutb model = mmPocontractorOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				log.info(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					lst.add(model);
				}
			}
			
			mmPocontractorOutbServ.Updated(lst);
		}else
			log.info(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 2:34:38 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param value_list
	 * @param error
	 * @throws Exception
	 */
	private void UpdateStagingWhenError(List<MmPocontractorOutb> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<MmPocontractorOutb> newlst = new ArrayList<MmPocontractorOutb>();
				for(MmPocontractorOutb model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new MmPocontractorOutbServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 2:34:43 PM 
	 * CreateBy=Chatree Siangklom
	 * List<MmPocontractorOutb>
	 * TODO
	 * @return
	 * @throws Exception
	 */
	private List<MmPocontractorOutb> Search() throws Exception 
	{
		String company = "SP";
		String project = "SPLVILLE-PRAGSA";
		//String documentNo = "CT-1204-000001";
		//String documentNo = "VO-1204-000001";
		//String documentNo = "VO-1204-000002";
		String documentNo = "VO-1204-000003";
		String subStatus = "A";
		String issync = "Y";
		List<MmPocontractorOutb> lst = mmPocontractorOutbServ.findByDocumentNo(company, project, documentNo, subStatus, issync);
		
		if(!CommonService.IsNull(lst))
			log.info(lst.size());
		else
			log.info(" else  ");
		
		return lst;
	}
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 2:34:46 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param value_list
	 * @throws Exception
	 */
	public void SendToSAP(List<MmPocontractorOutb> value_list) throws Exception {
		try{
			
			if(!CommonService.IsNull(value_list))
			{
				this.sap_bapi = "ZIN_MMPUR_PO_CONTRACT";
				this.sap_structure = "IM_PO_HEADER";
				this.sap_table = "T_PO_ITEM";
				this.sap_table_return = "RETURN";
				this.jco_conn  = new Connection();
				
				mmPocontractorOutbServ = new MmPocontractorOutbServices(this.emSynchro);
				
				//Get SAP BAPI function
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
									
				SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
			}
		}catch(Exception e){
			
			UpdateStagingWhenError(value_list, e);
			
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 2:34:50 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @throws Exception
	 */
	private void Start() throws Exception
	{
		this.sap_bapi = "ZIN_MMPUR_PO_CONTRACT";
		this.sap_structure = "IM_PO_HEADER";
		this.sap_table = "T_PO_ITEM";
		this.sap_table_return = "RETURN";
		this.jco_conn  = new Connection();
		
		mmPocontractorOutbServ = new MmPocontractorOutbServices(this.emSynchro);

		//Get SAP BAPI function
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
				
		
		List<MmPocontractorOutb> value_list = Search();	//mmPocontractorOutbServ.findAllIsSync("N");
		SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
	}

//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub		
//		try{
//			
//			VwSyncContractService obj = new VwSyncContractService();
//			
//			obj.Start();
//			
//		}catch(Exception ex)
//		{
//			log.error(ex);
//		}
//
//	}

}
